package com.ktjiaoyu.controller;
import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @return 13141
 * 2025/7/3
 * 10:35
 */
@Controller
@RequestMapping("/main/user")
public class SysUserController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    @RequestMapping("/page")
    public String page(Model model, SysUser condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Page<SysUser> page = null;
        try {
//            查询用户的分页信息
            page = sysUserService.findPage(condition, pageNo, pageSize);
//            查询所有的角色信息
            List<SysRole> roleList = sysRoleService.findAll();
//            将分页数据、角色列表和查询条件设置到模型数据中
            model.addAttribute("pageInfo", page);
            model.addAttribute("roleList", roleList);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 page 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "user/page";
    }

    @Resource(name = "toLocalUploadService") // 指定注入保存到本地硬盘的上传业务实现对象
    private UploadService uploadService;

//    跳转到 save.jsp 页面的接口
    @GetMapping("/save")
    public String toSave(Model model) {
        List<SysRole> roleList = null;
        try {
            roleList = sysRoleService.findAll();
//            有角色下拉框需要数据
            model.addAttribute("roleList", roleList);
//            回显数据时需要 sysUser, 这里给个空对象避免出错
            model.addAttribute("sysUser", new SysUser());
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 toSave()方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

//    保存或修改数据接口
    @PostMapping("/save")
    public String doSave(SysUser sysUser,
                         @RequestParam("idPic") MultipartFile idPic,
                         @RequestParam("workPic") MultipartFile workPic) {
//        允许的上传文件后缀
        String[] allowImageExt = {"jpg", "jpeg", "png", "gif", "bmp"};
        try {
//            上传证件照
            if (idPic != null) {
//                调用上传文件服务，返回上传成功后的路径，为 null 表示没上传
                String idPicPath = uploadService.uploadFile(idPic, allowImageExt);
                sysUser.setIdPicPath(idPicPath);
            }
//            上传工作照
            if (workPic != null) {
                String workPIcPath = uploadService.uploadFile(workPic, allowImageExt);
                sysUser.setWorkPicPath(workPIcPath);
            }
//            通过父类的 session 方法获取登录用户，由于泛型自动转换无需强转
            SysUser loginUser = session(Constants.SESSION_USER);
            if (sysUser.getId() == null) {
//                如果是添加用户，关联创建用户为当前登录用户
                sysUser.setCreatedUserId(loginUser.getId());
                sysUser.setCreatedTime(new Date());
            } else {
//                如果是修改用户，关联修改用户为当前登录用户
                sysUser.setUpdatedUserId(loginUser.getId());
                sysUser.setUpdatedTime(new Date());
            }
//            新增和修改公用同一个业务方法
            boolean ok = sysUserService.saveOrUPdate(sysUser);
            if (ok) {
//                保存成功，跳回列表界面
                return redirect("/main/user/page");
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 doSave 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }
//    根据 id 查询详细信息
    @ResponseBody
    @GetMapping(value = "/{id}/view")
    public Map ajaxView(@PathVariable("id") Long id,
                        Model model) {
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        SysUser info = null;
        try {
            info = sysUserService.findById(id);
            if (info != null) {
                resultMap.put("code", 200);
                resultMap.put("data", info);
            } else {
                resultMap.put("code", 500);
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 ajaxView 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        // return JSON.toJSONString(resultMap);
        return resultMap;
    }
//    查询用户信息并跳转修改页（共用 save.jsp）
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        SysUser sysUser = null;
        List<SysRole> roleList = null;
        try {
            sysUser = sysUserService.findById(id);
            roleList = sysRoleService.findAll();
//            有角色下拉框需要数据
            model.addAttribute("roleList", roleList);
//            回显数据时需要 sysUser,这里给个空对象避免出错
            model.addAttribute("sysUser", sysUser);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 toEdit方法执行出现错误。", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }
//    根据 account 查找用户
    @ResponseBody
    @GetMapping("/accountExist")
    public String accountExist(@RequestParam("account") String account) {
        LOGGER.debug("检查用户名 account={}的用户是否存在", account);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(account)) {
            resultMap.put("exist", 0);
        } else {
            try {
                SysUser sysUser = sysUserService.findByAccount(account);
                if (null != sysUser) {
//                    已经存在，设置为1
                    resultMap.put("exist", 1);
                } else {
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                LOGGER.error("SysUserController 中的" + "accountExist方法执行出现错误。", e);
                resultMap.put("error", "出现异常，请联系管理员处理！");
            }
        }
        return JSON.toJSONString(resultMap);
    }
    @ResponseBody
    @DeleteMapping("/del/{id}")
    public Map ajaxDel(@PathVariable("id") Long id,
                        Model model) {
        HashMap<String, Integer> resultMap = new HashMap<String, Integer>();
        Integer info = 0;
        try {
            info = sysUserService.deleteUser(id);
            if (info != 0) {
                resultMap.put("code", 200);
                resultMap.put("data", info);
            } else {
                resultMap.put("code", 500);
            }
        } catch (Exception e) {
            LOGGER.error("SysRoleController 中的 ajaxDel 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        // return JSON.toJSONString(resultMap);
        return resultMap;
    }
}
